package com.xexun.gpstracker.indoorlocation;

import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.*;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.webkit.*;
import android.widget.*;
import com.xexun.gpstracker.AppContext;
import com.xexun.gpstracker.base.GTFragment;
import com.xexun.gpstracker.channel.R;
import com.xexun.gpstracker.common.CommonRestPath;
import com.xexun.gpstracker.common.Constants;
import com.xexun.gpstracker.dialog.WizardAlertDialog;
import com.xexun.gpstracker.inter.HttpCallback;
import com.xexun.gpstracker.pojo.ResponseData;
import com.xexun.gpstracker.util.HttpUtil;
import com.xexun.gpstracker.util.JsonHttpResponseHelper;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.simple.eventbus.Subscriber;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import static android.content.ContentValues.TAG;

/**
 * 室内定位页面
 *
 * @author tfx
 */
public class IndoorFragment extends GTFragment implements OnClickListener {
    LinearLayout indoorLayout;
    private IndoorView indoorView;
    private ImageView imageView;
    private WebView webView;
    private Bitmap baseBitmap;
    private Canvas canvas;
    private Paint paint;
    private View view;
    private Context mContext;
    private Point[] point;
    String posStr;
    IndoorLoc.Position[] testPosition;
    int testIndex;
    private List<Integer> navigation;
    private int nvStart;    //导航开始点
    private int nvEnd;  //导航结束点
    private double scaleX;
    private double scaleY;

    public static IndoorFragment newInstance() {
        IndoorFragment newFragment = new IndoorFragment();
        return newFragment;
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
      /*  if(webView!=null){
            webView.destroy();
        }*/
        super.onDestroy();
    }

    private ConnectionRunnable connRunnable = new ConnectionRunnable();
    private class ConnectionRunnable implements Runnable {
        @Override
        public void run() {
            IndoorNavigation idNv = new IndoorNavigation();
            navigation = idNv.navigation(1,89);
            if(indoorView != null) {
                indoorView.invalidate();
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        nvStart = 0;
        nvEnd = 0;
        point = new Point[12];

        AppContext.getEventBus().register(this);

        testPosition = new IndoorLoc.Position[10];
        IndoorLoc loc = new IndoorLoc();
        testPosition[0] = loc.new Position("A000","XI01",-65,"XI02",-65,"XI03",-85,"XI04",-85);
        testPosition[1] = loc.new Position("A000","XI01",-70,"XI02",-80,"XI03",-70,"XI04",-85);
        testPosition[2] = loc.new Position("A000","XI01",-60,"XI02",-70,"XI03",-80,"XI04",-85);
        testPosition[3] = loc.new Position("A000","XI01",-75,"XI02",-60,"XI03",-85,"XI04",-80);
        testPosition[4] = loc.new Position("A000","XI01",-80,"XI02",-85,"XI03",-60,"XI04",-70);
        testPosition[5] = loc.new Position("A000","XI01",-85,"XI02",-80,"XI03",-70,"XI04",-60);
        testPosition[6] = loc.new Position("A000","XI01",-70,"XI02",-70,"XI03",-75,"XI04",-75);
        testPosition[7] = loc.new Position("A000","XI01",-80,"XI02",-80,"XI03",-70,"XI04",-65);
        testPosition[8] = loc.new Position("A000","XI01",-80,"XI02",-80,"XI03",-70,"XI04",-70);
        testPosition[9] = loc.new Position("A000","XI01",-85,"XI02",-85,"XI03",-70,"XI04",-70);
        testIndex = 0;
        //testPosition();
        //new Thread(connRunnable, "Connection Thread").start();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        //view = inflater.inflate(R.layout.fragment_indoor, container, false);
        //x.view().inject(this, view);

//        webView = (WebView) view.findViewById(R.id.posWV);
//
//        WebSettings mWebSettings = webView.getSettings();
//        mWebSettings.setJavaScriptEnabled(true);
//        mWebSettings.setBuiltInZoomControls(true);
//        mWebSettings.setLightTouchEnabled(true);
//        mWebSettings.setSupportZoom(true);
//        //mWebSettings.setLoadsImagesAutomatically(true);
//        mWebSettings.setDomStorageEnabled(true);
//        mWebSettings.setJavaScriptCanOpenWindowsAutomatically(true);
//        webView.requestFocus();
//        //mWebSettings.setLoadWithOverviewMode(true);
//        //mWebSettings.setUseWideViewPort(true);
//        //webView.setSaveEnabled(false);//让webview不保存状态，实际上对调用js没有用
//
//        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
//        webView.setWebViewClient(new WebViewClient() {
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                // 返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
//                view.loadUrl(url);
//                return true;
//            }
//        });
//        webView.loadUrl("file:///android_asset/html/index.html");
//
//        return view;

     /*   imageView = (ImageView) view.findViewById(R.id.indoorMapIV);
        imageView.post(new Runnable() {
            public void run() {
                //获得ImageView中Image的变换矩阵
                Matrix m = imageView.getImageMatrix();
                float[] values = new float[10];
                m.getValues(values);

                //Image在绘制过程中的变换矩阵，从中获得x和y方向的缩放系数
                float sx = values[0];
                float sy = values[4];
                Log.d(Constants.TAG, "scale_X = " + sx + ", scale_Y = " + sy);

                float x = imageView.getLeft();
                float y = imageView.getTop();
                float width = imageView.getWidth();
                float height = imageView.getHeight();
                float right = imageView.getRight();
                float bottom = imageView.getBottom();
                Log.i(Constants.TAG,"x:"+Float.toString(x)+" y:"+Float.toString(y)
                +" w:"+Float.toString(width)+" h:"+Float.toString(height)
                +" r:"+Float.toString(right)+" b:"+Float.toString(bottom)
                +" sx:"+Float.toString(imageView.getScaleX())
                +" sy:"+Float.toString(imageView.getScaleY()));
            }
        });
        // 初始化一个画笔，笔触宽度为5，颜色为红色
        paint = new Paint();
        paint.setStrokeWidth(5);
        paint.setColor(Color.RED);

        imageView.setOnClickListener(null);
        return view;*/

    /*    indoorLayout = (LinearLayout)view.findViewById(R.id.posLayout);
        imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                imageView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                ViewGroup.LayoutParams params = imageView.getLayoutParams();

                WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);

                int width = wm.getDefaultDisplay().getWidth();
                int height = wm.getDefaultDisplay().getHeight();

                indoorLayout.measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                int hh =  indoorLayout.getMeasuredHeight();
            }
        });*/

        indoorView = new IndoorView(mContext);
        indoorView.setOnTouchListener(new View.OnTouchListener(){
            @Override
            public boolean onTouch(View arg0, MotionEvent arg1) {
                // TODO Auto-generated method stub
                int x, y;
                //Log.i(Constants.TAG,"rawx="+String.valueOf(arg1.getRawX())+"rawy="+String.valueOf(arg1.getRawY())+"\n");
                x = (int)arg1.getX();
                y = (int)arg1.getY();
                Log.i(Constants.TAG,"x="+String.valueOf(x)+"y="+String.valueOf(y)+"\n");
                x = (int)(x/scaleX);
                y = (int)(y/scaleY);

                int action =arg1.getAction();
                if(action==MotionEvent.ACTION_MOVE){
                    System.out.println("yidong");
                }
                if(action==MotionEvent.ACTION_DOWN){
                    System.out.println("down");
                }
                if(action==MotionEvent.ACTION_UP){
                    System.out.println("up");
                    if(nvStart == 0) {
                        if(navigation != null) {
                            navigation.clear();
                            navigation = null;
                        }
                        nvStart = findNearPoint(x, y);
                        nvEnd = 0;
                    } else if(nvEnd == 0) {
                        nvEnd = findNearPoint(x, y);
                        if(nvEnd == nvStart) {
                            nvEnd = 0;
                            return false;
                        }
                        IndoorNavigation idNv = new IndoorNavigation();
                        navigation = idNv.navigation(nvStart,nvEnd);
                        if(indoorView != null) {
                            indoorView.invalidate();
                        }

                        nvStart = 0;
                        nvEnd = 0;
                    }
                }
                if(action==MotionEvent.ACTION_CANCEL){
                    System.out.println("cancel");
                }

                return false;
            }

        });
        indoorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppContext.getEventBus().post(v, Constants.EVENT_TAG_POSITION);
            }
        });

        return indoorView;
    }

    private int findNearPoint(int x, int y) {
        List<DistanceNode> dNode = new ArrayList<DistanceNode>();
        for(int i=1; i<MapPoint.points.size(); i++) {
            Point point = MapPoint.points.get(i).point;
            dNode.add(new DistanceNode(IndoorNavigation.getDistance(new Point(x,y), point), i));
        }

        Collections.sort(dNode, new Comparator<DistanceNode>() {
            @Override
            public int compare(DistanceNode lhs, DistanceNode rhs) {
                if(lhs.distance - rhs.distance < -0.000001) {
                    return -1;
                } else {
                    return 1;
                }
            }
        });

        return dNode.get(0).index;
    }

    @Subscriber(tag = Constants.EVENT_TAG_POSITION)
    private void updateTermBindStatus(View v) {
        testIndex++;
        if(testIndex >= 10)
            testIndex = 0;
        testPosition();
        indoorView.invalidate();
    }

    public void testPosition() {
        IndoorLoc loc = new IndoorLoc();
        posStr = loc.indoorLocation(testPosition[testIndex]);
    }

    @Override
    public void onClick(View v) {

    }

    private void initEvent() {

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void initView() {

    }

    @Override
    public void setCurrImei(String imei) {

    }

    @Override
    public void setPosition(String position) {

    }

    @Override
    public void closeTimer() {

    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     *
     * @param context
     * @param dpValue
     * @return
     * @author SHANHY
     * @date   2015年10月28日
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     *
     * @param context
     * @param pxValue
     * @return
     * @author SHANHY
     * @date   2015年10月28日
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public class IndoorView extends SurfaceView {
        public IndoorView(Context context) {
            super(context);
            setBackgroundResource(R.drawable.indoormap);

            setZOrderOnTop(true);//使surfaceview放到最顶层
            getHolder().setFormat(PixelFormat.TRANSLUCENT);//使窗口支持透明度
        }

        private void drawPointText(int index,Canvas canvas,Paint paint) {
            paint.setTextSize(40);
            String posStr = MapPoint.points.get(index).name;
            if(posStr == "") {
                posStr = "过道";
            }
            Rect bounds = new Rect();
            paint.getTextBounds(posStr, 0, posStr.length(), bounds);
            Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
            int x = MapPoint.points.get(index).point.x;
            x *= scaleX;
            int y = MapPoint.points.get(index).point.y;
            y *= scaleY;

            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.BLUE);
            canvas.drawCircle(x,y,10,paint);

            x -= bounds.right/2;
            if(x < 0) {
                x = 0;
            } else if(x + bounds.right > getWidth()) {
                x = getWidth() - bounds.right;
            }

            int offsetY = (fontMetrics.bottom + fontMetrics.top)/2 - fontMetrics.top;
            y += offsetY;
            paint.setColor(Color.GREEN);
            canvas.drawText(posStr, x, y, paint);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            //canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);//绘制透明色

            Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), R.drawable.indoormap);
            int height = bitmap.getHeight();
            int width = bitmap.getWidth();
            bitmap.recycle();

            int wd = getWidth(); //px
            int ht = getHeight();

            scaleX = (double)wd/(double)width;
            scaleY = (double)ht/(double)height;

            paint = new Paint();
            paint.setStrokeWidth(5);
            paint.setAntiAlias(true);

            if(nvStart != 0) {
                drawPointText(nvStart,canvas,paint);
            }
            if(nvEnd != 0) {
                drawPointText(nvEnd,canvas,paint);
            }
            if(navigation != null) {
                paint.setColor(Color.RED);
                for (int i = 0; i < navigation.size()-1; i++) {
                    int start = navigation.get(i);
                    int end = navigation.get(i + 1);
                    Point st = MapPoint.points.get(start).point;
                    int startX = (int) (scaleX * st.x);
                    int startY = (int) (scaleY * st.y);
                    Point ed = MapPoint.points.get(end).point;
                    int endX = (int) (scaleX * ed.x);
                    int endY = (int) (scaleY * ed.y);
                    canvas.drawLine(startX, startY, endX, endY, paint);
                }
                drawPointText(navigation.get(0),canvas,paint);
                drawPointText(navigation.get(navigation.size()-1),canvas,paint);
            }

            // 首先定义一个paint
          /*  Paint paint = new Paint();

            // 绘制矩形区域-实心矩形
            // 设置颜色
            paint.setColor(Color.WHITE);
            // 设置样式-填充
            paint.setStyle(Paint.Style.FILL);
            // 绘制一个矩形
            int width = getWidth(); //px
            int height = getHeight();
            canvas.drawRect(new Rect(0, 0, width, height), paint);

            int corridorWidth = width/9;
            int seatWidth = (width - 2*corridorWidth)/3;
            int seatHeight = (height - corridorWidth)/2;

            paint.setColor(Color.GRAY);
            paint.setStyle(Paint.Style.FILL);
            for(int i=0; i<3; i++) {
                for(int j=0; j<2; j++) {
                    canvas.drawRect(new Rect(i*(seatWidth+corridorWidth), j*(seatHeight+corridorWidth),
                            i*(seatWidth + corridorWidth)+seatWidth, j*(seatHeight+corridorWidth)+seatHeight), paint);
                }
            }

            int textSize = seatWidth/3;
            int pxSize = IndoorFragment.px2dip(mContext,textSize);
            paint.setTextSize(pxSize);    //dp,TextView.setTextSize--sp
            for(int m=0; m<2; m++) {
                for (int i = 0; i < 3; i++) {
                    for (int j = 0; j < 2; j++) {
                        paint.setColor(Color.GREEN);
                        canvas.drawRect(new Rect(i*(seatWidth + corridorWidth)+(seatWidth/2), m*(seatHeight+corridorWidth)+j*(seatHeight/2),
                                i*(seatWidth+corridorWidth)+seatWidth, m*(seatHeight+corridorWidth)+j*(seatHeight/2)+seatWidth/2), paint);

                        paint.setColor(Color.BLACK);
                        String STR_FORMAT = "00";
                        DecimalFormat df = new DecimalFormat(STR_FORMAT);
                        int index = i*4 + j + m*2;
                        String posStr = "A0" + df.format(index + 1);
                        Rect bounds = new Rect();
                        paint.getTextBounds(posStr, 0, posStr.length(), bounds);
                        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
                        int x = i*(seatWidth + corridorWidth)+(seatWidth/2);

                        int offsetX = (IndoorFragment.px2dip(mContext,seatWidth)-bounds.right)/2;
                        x += offsetX;
                        int offsetY = (IndoorFragment.px2dip(mContext,seatWidth)-fontMetrics.bottom + fontMetrics.top)/2 - fontMetrics.top;
                        int y = m*(seatHeight+corridorWidth)+j*(seatHeight/2) + offsetY;
                        canvas.drawText(posStr, x, y, paint);

                        if(point[index] == null) {
                            point[index] = new Point(x-offsetX, y+offsetY);
                        }
                    }
                }
            }

            if(posStr != null) {
                int pos = Integer.parseInt(posStr.substring(1));
                paint.setColor(Color.RED);
                canvas.drawText("你在这", point[pos - 1].x, point[pos - 1].y, paint);
            }*/

            // 绘空心矩形
            // 设置颜色
         /*   paint.setColor(Color.RED);
            // 设置样式-空心矩形
            paint.setStyle(Paint.Style.STROKE);
            // 绘制一个矩形
            canvas.drawRect(new Rect(10, 10, 100, 30), paint);*/

            // 绘文字
            // 设置颜色
            //paint.setColor(Color.GREEN);
            // 绘文字
            //canvas.drawText("Hello", 10, 50, paint);

            // 绘图
            // 从资源文件中生成位图
            //Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
            // 绘图
            //canvas.drawBitmap(bitmap, 10, 60, paint);
        }
    }

    private class DistanceNode {
        public double distance;
        public int index;

        public DistanceNode(double d, int idx) {
            distance = d;
            index = idx;
        }
    }
}
